/**
思路：
1、css控制文字超出显示省略号
2、绑定title，鼠标悬浮显示完整文字
3、修改悬浮显示样式
使用示例
<template>
  <span v-textOver='10'>我是文字我是文字我是文字我是文字我是文字我是文字我是文字</span>
</template>
 */

import Vue from 'vue';

//自定义title样式
const myTitleStyle =
    'position: absolute;color: #ffffff;font-size: 14px;padding: 4px;background: rgba(40, 40, 40, 0.8);border-radius:5px;z-index:999;';

const setStyle = el => {
    let newtitle = '';
    let intoTitle = false;
    el.onmouseover = function (e) {
        newtitle = el.getAttribute('title');
        el.setAttribute('title', '');
        if (newtitle !== '' && !document.getElementById('myTextOverTitle')) {
            let div = document.createElement('div');
            div.setAttribute('id', 'myTextOverTitle');
            div.innerText = newtitle;
            document.body.appendChild(div);
        }
        const myTextOverTitleEl = document.getElementById('myTextOverTitle');
        myTextOverTitleEl.style.left = e.pageX + 'px';
        myTextOverTitleEl.style.top = e.pageY + 'px';
        myTextOverTitleEl.style.cssText += myTitleStyle;
        //鼠标移入title改变状态标识，可用于后续进行复制文字
        myTextOverTitleEl.onmouseover = function () {
            intoTitle = true;
        };
        //鼠标移出title时删除自定义的title元素
        myTextOverTitleEl.onmouseout = function () {
            intoTitle = false;
            document.body.removeChild(myTextOverTitleEl);
        };
    };
    el.onmouseout = function () {
        el.setAttribute('title', newtitle);
        const myTextOverTitleEl = document.getElementById('myTextOverTitle');
        // 延时关闭，鼠标移入title可进行复制文字
        setTimeout(() => {
            if (!intoTitle && document.body.contains(myTextOverTitleEl)) {
                document.body.removeChild(myTextOverTitleEl);
            }
        }, 0);
    };
    el.onmousemove = function (e) {
        const myTextOverTitleEl = document.getElementById('myTextOverTitle');
        myTextOverTitleEl.style.left = e.pageX + 'px';
        myTextOverTitleEl.style.top = e.pageY + 'px';
    };
};

const textOver = Vue.directive('textOver', {
    inserted(el, binding) {
        el.setAttribute('title', el.innerText);
        let div = document.createElement('div');
        el.parentNode.appendChild(div);
        div.appendChild(el);
        // 入参指定最大显示字符数
        if (binding.value) {
            // +4的作用是(... )占4个字符
            div.style.width =
                (binding.value + 4) * parseInt(window.getComputedStyle(el).fontSize) + 'px';
        }
        div.style.textOverflow = 'ellipsis';
        div.style.whiteSpace = 'nowrap';
        div.style.overflow = 'hidden';
        setStyle(el);
    },
});

export { textOver };
